#include <ESP8266WiFi.h>
#include <WiFiServer.h>
#include <Wire.h>   //用于I2C通信
#include <I2Cdev.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_MPU6050.h>

Adafruit_MPU6050 mpu;

const char* ssid = "凌";
const char* password = "92921bc46140";
const int serverAPort = 8080;

WiFiServer serverA(serverAPort);
WiFiClient clientA;

void setup() {
  Serial.begin(115200);
  Wire.begin(D2, D1);//初始化I2C通信
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  mpu.setGyroRange(MPU6050_RANGE_500_DEG);//设置陀螺仪量程
  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);//设置滤波器带宽

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi");
  serverA.begin();
  Serial.println("Server started");
}

void loop() {
  clientA = serverA.available();//检查是否有客户端连接到服务器A
  if (clientA) {
    Serial.println("Client connected to Server A");
    while (clientA.connected()) {
      sensors_event_t a,g,temp;
      mpu.getEvent(&a,&g,&temp);
      String datat = String(g.gyro.x) + "," + String(g.gyro.y) + "," + String(g.gyro.z);
      String dataj = String(a.acceleration.x) + "," + String(a.acceleration.y) + "," + String(a.acceleration.z);
      clientA.println(datat+dataj);
      delay(500); // 每秒发送一次数据
    }
    clientA.stop();
    Serial.println("Client disconnected from Server A");
  }
}

void connectToWiFi() {
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}